<template>
  <div class="app-page">
    <aside-tree
      title="安检任务单"
      :tree-data="treeData"
      :mouse-button="false"
      :loading="$loadingPlugin.getTreeData"
      @currentChange="currentChange"
      @refresh="getTreeData"
    />
    <div class="table">
      <el-table-form ref="form">
        <el-form-item class="merge-item">
          <el-select v-model="conditionType" style="width: 180px; margin-right: 2px;">
            <el-option label="客户电话" value="csmPhone" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <el-option label="客户地址" value="csmAddress" />
            <el-option label="派单人" value="createUser" />
            <el-option label="处理人" value="checkUser" />
            <el-option label="关联安检单号" value="checkId" />
          </el-select>
          <el-input v-model="conditionText" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item :table-form-merge="2" class="merge-item">
          <el-select v-model="timeType" style="width: 170px; margin-right: 2px;">
            <el-option label="派单时间" value="createTime" />
            <el-option label="处理时间" value="auditDt" />
          </el-select>
          <el-date-picker
            v-model="date"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item class="merge-item" label="客户类型">
          <el-select v-model="query.csmType" style="width: 170px; margin-right: 2px;" placeholder="请选择">
            <el-option v-for="(i, ind) in clientList" :key="ind" :label="i.desc" :value="i.value" />
          </el-select>
        </el-form-item>
        <el-form-item class="merge-item" label="状态">
          <el-select v-model="query.planDetailStatus" style="width: 170px; margin-right: 2px;" placeholder="请选择">
            <el-option v-for="(i, ind) in enumerationType" :key="ind" :label="i.desc" :value="i.value" />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;" class="btn-group">
        <div>
          <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :immediate-fetch="false"
        default-open
        @fetch="fetchData"
      />
    </div>
    <add ref="add" />
    <check-roam-info ref="roamInfo" />
    <check-transfer ref="transferOrder" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import AsideTree from '@/views/components/OrgTree'
  import { organizationQueryList, queryMap, queryCsmTypeMap, gasCheckTodoList, gasCheckTodoExport, queryExportDomain, gasCheckTodoCancellation } from '@/api'
  import moment from 'dayjs'
  import Add from './components/Add.vue'
  import CheckRoamInfo from './components/CheckRoamInfo'
  import CheckTransfer from './components/CheckTransfer'

  export default {
    name: 'addition',
    components: {
      AsideTree,
      CheckRoamInfo,
      CheckTransfer,
      Add
    },
    data() {
      return {
        treeData: [],
        clientList: [],
        enumerationType: [],
        actionColWidth: 80,
        exportDomain: {},
        query: {
          orgSNNo: '',
          csmType: '',
          planDetailStatus: '',
          pageIndex: '',
          pageSize: ''
        },
        conditionText: '',
        conditionType: 'csmPhone',
        timeType: 'createTime',
        date: [moment().startOf('month'), moment().endOf('hour')],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 100
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 100
          },
          {
            prop: 'csmType',
            label: '客户类型',
            width: 100,
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.clientList, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'contact',
            label: '联系人',
            width: 100
          },
          {
            prop: 'csmAddress',
            label: '联系地址',
            width: 260,
            render: (h, { row }) => {
              const s = row.provinceName && row.provinceName
              const v = row.cityName && row.cityName
              const x = row.countryName && row.countryName
              const z = row.csmAddress && row.csmAddress
              const q = row.streetName && row.streetName
              return <span>{s}{v}{x}{q}{z}</span>
            }
          },
          {
            prop: 'csmPhone',
            label: '联系电话',
            width: 100
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 150
          },
          {
            prop: 'checkUser',
            label: '处理人',
            width: 100
          },
          {
            prop: 'auditDt',
            label: '处理时间',
            width: 150,
            render: (h, { row }) => <span>{ row.planDetailStatus === 2 && row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'createUser',
            label: '派单人',
            width: 100
          },
          {
            prop: 'createTime',
            label: '派单时间',
            width: 150,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'planDetailStatus',
            label: '状态',
            width: 100,
            render: (h, { row }) => <span>{ row.planDetailStatus && formatColumnMap(this.enumerationType, 'value', row.planDetailStatus, 'desc') }</span>
          },
          {
            prop: 'checkId',
            label: '关联安检单',
            width: 100,
            render: (h, { row }) => {
              if (row.checkId === 0) {
                return ''
              }
              return <span>{row.checkId}</span>
            }
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-link size='mini' onClick={() => this.openFlow(row)}>流转信息</el-link>
                  { row.planDetailStatus === 1 && <el-link size='mini' onClick={() => this.openTransferOrder(row)}>转派</el-link>}
                  { row.planDetailStatus === 1 && <el-link size='mini' onClick={() => this.cancellation(row)}>作废</el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTreeData()
      await this.getUserType()
      await this.queryOptionsMap()
      await this.getExportDomain()
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        this.query.pageIndex = currentPage
        this.query.pageSize = pageSize
        const params = {
          ...this._getQuery(this.query)
        }
        this.conditionText ? params[this.conditionType] = this.conditionText : ''
        if (this.date && this.date.length === 2) {
          params[this.timeType] = moment(this.date[0]).format()
          params[`${this.timeType}End`] = moment(this.date[1]).format()
        }
        const res = await gasCheckTodoList(params)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询
      async search() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 新增
      async add(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          gasCheckTodoExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 点击流转信息
      async openFlow(row) {
        await this.$refs.roamInfo.open(row)
      },
      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 作废
      cancellation(val) {
        const me = this
        // console.log('val', val)
        this.$confirm('作废安检任务单，确定要执行吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await gasCheckTodoCancellation({ planCode: val.planCode, csmAddressId: val.csmAddressId })
          console.log('res', res)
          if (res.status === 200) {
            me.$message({
              type: 'success',
              message: '作废安检任务成功!'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // })
        })
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 选择组织机构变化
      currentChange(current) {
        if (current.orgSNNo) {
          this.query.orgSNNo = current.orgSNNo
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          this.$message({
            message: '请选择机构',
            type: 'warning'
          })
        }
      },
      // 获取组织机构数据
      async getTreeData() {
        const res = await organizationQueryList({})
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 客户类型
      async getUserType() {
        try {
          const res = await queryCsmTypeMap()
          this.clientList = res.data
        } catch (error) {
          console.log(error)
        }
      },
      // 状态枚举
      async queryOptionsMap() {
        try {
          const res = await queryMap({ enumName: 'PlanDetailStatus' })
          this.enumerationType = res.data // 状态枚举
        } catch (error) {
          console.log(error)
        }
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  height: calc(100vh - 125px);
  padding: 0;
  .table {
    width: calc(100% - 270px);
    margin-left: 10px;
  }
}
</style>
